#!/bin/sh /etc/rc.common

{
	START=90
	STOP=10
	USE_PROCD=1
}

_validate_section() {
	uci_validate_section omr-quota "$1" "$2" \
		'txquota:uinteger'  \
		'rxquota:uinteger'  \
		'ttquota:uinteger'  \
		'interval:uinteger:30' \
		'enabled:bool:0'
}

_launch_quota() {
	local txquota rxquota ttquota interval enabled interface
	_validate_section "interface" "$1"
	interface=$(ifstatus "$1" | jsonfilter -q -e '@["l3_device"]')
	[ -n "$(echo $interface | grep '@')" ] && interface=$(ifstatus "$1" | jsonfilter -q -e '@["device"]')

	[ -z "$interface" ] && return

	[ -z "$txquota" ] && [ -z "$rxquota" ] && [ -z "$ttquota" ] && return
	[ "$enabled" = "0" ] && return

	[ "$(uci get vnstat.@vnstat[-1].interface | grep $interface)" = "" ] && {
		uci -q batch <<-EOF
			add_list vnstat.@vnstat[-1].interface=$interface
		EOF
	}

	procd_open_instance
	procd_set_param command /bin/omr-quota "$interface"
	procd_append_param env "OMR_QUOTA_TX=$txquota"
	procd_append_param env "OMR_QUOTA_RX=$rxquota"
	procd_append_param env "OMR_QUOTA_TT=$ttquota"
	procd_append_param env "OMR_QUOTA_INTERVAL=$interval"
	procd_set_param respawn 0 10 0
	procd_set_param stderr 1
	procd_close_instance
}

start_service() {
	config_load omr-quota
	config_foreach _launch_quota interface
}

service_triggers() {
	procd_add_reload_trigger omr-quota network
}

reload_service() {
	stop
	start
}
